package xyz.flowlight.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.flowlight.domain.entity.Cart;
import xyz.flowlight.domain.entity.Product;
import xyz.flowlight.domain.response.ResponseResult;
import xyz.flowlight.domain.vo.CartPageVO;
import xyz.flowlight.domain.vo.CartVO;
import xyz.flowlight.mapper.CartMapper;
import xyz.flowlight.service.CartService;
import xyz.flowlight.service.ProductService;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Resource
     CartMapper cartMapper;

    @Resource
    ProductService productService;

    @Override
    public ResponseResult<Void> addToCart(Integer userId, Integer productId, Integer quantity) {
        // 检查商品是否已经存在购物车中
        Cart existingCart = cartMapper.findByUserIdAndProductId(userId, productId);
        if (existingCart != null) {
            // 如果存在，更新数量
            existingCart.setQuantity(existingCart.getQuantity() + quantity);
            cartMapper.updateById(existingCart);
        } else {
            // 如果不存在，新增商品
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            cartMapper.insert(cart);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<List<Cart>> getCartItems( Integer userId) {
        List<Cart> cartItems = cartMapper.findByUser(userId);
        return ResponseResult.success(cartItems);
    }

    @Override
    public BigDecimal calculateTotal(Integer userId) {
        List<Cart> cartItems = cartMapper.findByUser(userId);
        BigDecimal total = BigDecimal.ZERO;

        for (Cart cartItem : cartItems) {
            Product product = productService.getById(cartItem.getProductId());
            if (product != null) {
                BigDecimal itemTotal = product.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity()));
                total = total.add(itemTotal);
            }
        }

        return total;
    }

    @Override
    public ResponseResult<CartPageVO> getCartList(Integer userId) {
        List<CartVO> cartVOList = cartMapper.findByUser(userId).stream()
                .map(cart -> {
                    Product product = productService.getById(cart.getProductId());
                    return new CartVO(
                            cart.getCartId(),
                            product.getName(),
                            cart.getQuantity(),
                            product.getPrice()
                    );
                })
                .collect(Collectors.toList());

        Integer totalPrice = cartVOList.stream()
                .map(cartVO -> cartVO.getPrice().multiply(BigDecimal.valueOf(cartVO.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .intValue();

        CartPageVO cartPageVO = new CartPageVO();
        cartPageVO.setCartVO(cartVOList);
        cartPageVO.setTotalPrice(totalPrice);

        return ResponseResult.success(cartPageVO);
    }

    @Override
public void updateQuantity(Long cartId, Integer quantity) {
    Cart cart = cartMapper.selectById(cartId);
    if (cart == null) {
        throw new RuntimeException("购物车项不存在");
    }
    if (quantity <= 0) {
        throw new RuntimeException("数量必须大于0");
    }
    cart.setQuantity(quantity);
    cartMapper.updateById(cart);
}
}
